package logic

import (
	"context"
	"fmt"
	"shopping-mall/models"
	"shopping-mall/pkg"

	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRestLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRestLogic {
	return &UserRestLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRestLogic) UserRest(in *shopping_rpc.UserRestRequest) (*shopping_rpc.UserRestResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	key := fmt.Sprintf("%s:%s", "rest", in.Phone)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	if models.DB.Where("account = ?", in.Phone).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("账号已注册")
	}
	user.Account = in.Phone
	user.Password = pkg.MD5(in.Phone)
	if models.DB.Create(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &shopping_rpc.UserRestResponse{
		Account:  in.Phone,
		Password: in.Phone,
	}, nil
}
